package com.doubao.service;

import com.doubao.config.properties.WxProperties;
import com.doubao.exception.BusinessException;
import com.doubao.response.WxLoginResponse;
import com.fasterxml.jackson.core.JsonProcessingException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

@Slf4j
@Service
@RequiredArgsConstructor
public class WxService {
    private final WxProperties wxProperties;
    private final RestTemplate restTemplate;
    private static final String WX_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";

    public WxLoginResponse getWxSession(String code) {
        // 构建请求URL
        String url = String.format("%s?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code",
                WX_LOGIN_URL,
                wxProperties.getAppId(),
                wxProperties.getSecret(),
                code);

        try {
            // 直接使用 getForObject 获取 JSON 响应并转换为 WxLoginResponse 对象
            WxLoginResponse response = restTemplate.getForObject(url, WxLoginResponse.class);

            // 空值检查
            if (response == null) {
                log.error("微信登录失败: 接口返回为空");
                throw new BusinessException("微信登录失败，请重试");
            }

            // 错误码检查
            if (response.getErrcode() != null && !"0".equals(response.getErrcode())) {
                log.error("微信登录失败，错误码：{}，错误信息：{}",
                    response.getErrcode(), response.getErrmsg());
                throw new BusinessException("微信登录失败，请重试");
            }

            return response;

        } catch (RestClientException e) {
            log.error("调用微信接口失败", e);
            throw new BusinessException("微信登录失败，请重试");
        }
    }
}